package cn.consult.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @ Author：周xx
 * @ Date：2024-04-10-11:10
 * @ Version：1.0
 * @ Description：
 */
public class NettyServerHandle extends ChannelInboundHandlerAdapter {
    private static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 注册时执行
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注册");
    }

    /**
     * 注销时执行
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("注销");
    }

    /**
     * 激活时执行
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("激活");
        //当前会话加入管道组中
        channels.add(ctx.channel());
    }

    /**
     * 断开时执行
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开");
        //当前会话从管道组中移出
        channels.remove(ctx.channel());
    }

    /**
     * 读取数据时执行
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.err.println("服务器读取线程 " + Thread.currentThread().getName());
        System.out.println("server ctx =" + ctx);
        System.out.println("看看 channel 和 pipeline 的关系");

        Channel channel = ctx.channel();


        //将 msg 转成一个 ByteBuf,ByteBuf 是 Netty 提供的，不是 NIO 的 ByteBuffer.
        String buf = (String) msg;
//        String str = new String(buf.getByte(0),"UTF-8");
        System.out.println("客户端发送消息是:" + buf);
        System.out.println("客户端地址:" + channel.remoteAddress());
    }

    /**
     * 读取数据完后执行
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        String replyStr = "FE FE 68 00 00 42 89 AA AA 68 01 02 65 F3 27 16";
        byte[] b = fromHexString(replyStr);
        ctx.writeAndFlush(Unpooled.copiedBuffer(b));
        System.out.println("向客户端发送：" + replyStr);
        ctx.flush();
    }

    public byte[] fromHexString(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        hexStr = hexStr.replaceAll(" ", "");
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;

    }

    /**
     * 用户事件
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("用户事件");
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("可写状态变更为" + ctx.channel().isWritable());
    }

    /**
     * 通道发生异常事件
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常");
        System.out.println(cause.getMessage());
    }
}
